package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.params.BaseParam;
import com.cskaoyan.bean.params.RoleCreateBO;
import com.cskaoyan.mapper.LabelMapper;
import com.cskaoyan.mapper.RoleMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.System;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @USER: cuiweiguo#
 * @DATE: 2022/5/6
 * @TIME: 11:05
 * @PROJECT_NAME: mallproject2
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleMapper roleMapper;

    @Autowired
    LabelMapper labelMapper;

    @Override
    public RoleListBean list(String name, BaseParam baseParam) {
        //查询总共所有的数量
        Integer page = baseParam.getPage();//页码
        Integer limit = baseParam.getLimit();//数据量
        String sort = baseParam.getSort();//排序列
        String order = baseParam.getOrder();//desc\asc
        //分页插件 PageHelper，辅助我们做分页以及分页信息的获得
        PageHelper.startPage(page, limit);
        //执行查询过程中拼接分页信息
        //  username="%"+username+"%";

        List<Role> list = roleMapper.select(sort, order, name);

        //total、pages、list
        //通过PageHelper帮我们来获得一些和分页相关的信息PageInfo
        //使用其有参构造方法 → 形参写来源于数据库的list
        PageInfo<Role> pageInfo = new PageInfo<>(list);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        return RoleListBean.data(total, pages, limit, page, list);
    }

    @Override
    public RoleListBean options() {
        int count = roleMapper.countAll();
        //查询总共所有的数量
        Integer page = 1;//默认一页显示
        String sort = "id";//默认
        String order = "desc";

        //分页插件 PageHelper，辅助我们做分页以及分页信息的获得
        PageHelper.startPage(page, count);
        //执行查询过程中拼接分页信息
        List<RoleVO> list = roleMapper.selectAll(sort, order);
        PageInfo<RoleVO> pageInfo = new PageInfo<>(list);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        Integer limit = count;//数据量
        return RoleListBean.data(total, pages, limit, page, list);
       /* //查询数据库获得角色级别总量
        int count = labelMapper.countAll();
        //查询总共所有的数量
        Integer page = 1;//默认一页显示
        String sort = "id";//默认
        String order = "desc";
        //分页插件 PageHelper，辅助我们做分页以及分页信息的获得
        PageHelper.startPage(page,count);
        //执行查询过程中拼接分页信息
        List<LabelVO> list = labelMapper.selectAll(sort, order);
        //total、pages、list
        //通过PageHelper帮我们来获得一些和分页相关的信息PageInfo
        //使用其有参构造方法 → 形参写来源于数据库的list
        PageInfo<LabelVO> pageInfo = new PageInfo<>(list);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        Integer limit = count;//数据量
        return LabelListBean.data(total, pages, limit, page, list);*/
    }

    @Override
    public RoleCreateVO create(RoleCreateBO roleCreateBO) {
        Role role = new Role(null, roleCreateBO.getName(), roleCreateBO.getDesc(), null, new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis()), null);
        int affectedRows = roleMapper.insertSelective(role);
        if (affectedRows == 1) {
            return new RoleCreateVO(role.getId(), role.getName(), role.getDesc(), role.getAddTime(), role.getUpdateTime());
        }
        return null;
    }

    @Override
    public int delete(Role role) {
        //业务应该是一个虚假删除
        //实际应该是改变deleted的值
        Role newRole = new Role(role.getId(), null, null, null, null, new Date(System.currentTimeMillis()), true);
        int affectedRows = roleMapper.updateByPrimaryKeySelective(newRole);
        //int affectedRows = roleMapper.updateDeletedByPrimaryKey(role);
        if (affectedRows == 1) {
            return 200;
        } else {
            return 0;
        }
    }

    @Override
    public int update(Role role) {
        //传递的是名称和说明--还需要改更新时间
        Role newRole = new Role(role.getId(), role.getName(), role.getDesc(), null, null, new Date(System.currentTimeMillis()), null);
        int affectedRows = roleMapper.updateByPrimaryKeySelective(newRole);
        if (affectedRows == 1) {
            return 200;
        }
        return 0;
    }

    @Override
    public RolePermissions getPermissionsByRoleId(Integer roleId) {
        //先获得所有关于权限的数据
        RolePermissions rolePermissions = new RolePermissions();
        //先实现显示所有的父类权限
        List<SystemPermissions> systemPermissions = roleMapper.selectPerssionsByRoleId(roleId);
        Iterator<SystemPermissions> iterator = systemPermissions.iterator();
        while (iterator.hasNext()) {
            SystemPermissions permissions = iterator.next();
            String permissionsId = permissions.getId();
            //显示所有子类权限
            List<AuthChildren> authChildrenList = roleMapper.queryChildrenPermissonsById(permissionsId);
            Iterator<AuthChildren> childrenIterator = authChildrenList.iterator();
            while (childrenIterator.hasNext()) {
                AuthChildren authChildren = childrenIterator.next();
                String authChildrenId = authChildren.getId();
                List<OptionsChildren> optionsChildrenList = roleMapper.queryOptionChlidrenById(authChildrenId, permissionsId);
                authChildren.setChildren(optionsChildrenList);
            }
            permissions.setChildren(authChildrenList);
        }
        //再获得对应角色所拥有的角色
        //List<String> strings = roleMapper.getPermissionsByRoleId(roleId);
        //TODO:这里应该考虑数据库值为  * 的回显
        String[] strings = roleMapper.getPermissionsByRoleId(roleId).toArray(new String[0]);
        rolePermissions.setSystemPermissions(systemPermissions);
        rolePermissions.setAssignedPermissions(strings);
        return rolePermissions;
    }

    /**
     * @Description:
     * @Author: cuiweiguo#
     * @Date: 2022/5/9 23:10
     * @Param: [roleId, permissions]:
     * @return: int:
     **/
    @Override
    public int postPermissions(Integer roleId, String[] permissions) {
        //TODO：为了避免冲突或者更复杂的业务，将所有对应的权限先全部逻辑删除，然后插入现在的所有权限
        //先根据id将所有的权限逻辑删除
        int affectedRows1 = roleMapper.updateDeletePermissionsByRoleId(roleId);

        //插入更新后的权限
        int affectedRows = roleMapper.insertPermissions(roleId, permissions);
        if(affectedRows==permissions.length){
            return 200;
        }
        return 0;
    }
}
